import { RewardLog, RewardV2 } from '@/api/draw'
import { GetUserInfo } from '@/api/user'
import BgImage from '@/assets/bg.jpg'
import DrawDipan from '@/assets/draw-bottom.png'
import DrawBg from '@/assets/draw-pan-bg.png'
import DrawStartButton from '@/assets/draw-start-button.png'
import Subtitle from '@/assets/draw-subtitle.png'
import Title from '@/assets/draw-title.png'
import MyPrizeButton from '@/assets/my-p-button.png'
import ChannelLogo from '@/components/ChannelLogo'

import MallLinkButton from '@/components/MallLinkButton'
import useCaptchaBox from '@/components/useCaptchaBox'
import { XyzTransitionGroup } from '@animxyz/react'

import { LuckyWheel } from '@lucky-canvas/react'
import classNames from 'classnames'
import { useRef, useState } from 'react'
import { Toast } from 'react-vant'
import { history, useMutation, useQuery } from 'umi'

import styles from './index.module.less'
import '@animxyz/core'

export default function Page() {
  // 获取用户信息
  const { data: user, refetch: refetchUser } = useQuery(['get/user/info'], GetUserInfo)

  const myLucky = useRef<any>(null)

  const [isSpinning, setIsSpinning] = useState<boolean>(false)

  const [prizes] = useState([
    {
      id: 136,
      name: '墨迹会员月卡',
      // fonts: [{ text: '0' }],
    },
    {
      id: 999,
      name: '再来一次',
      // fonts: [{ text: '1' }],
    },
    {
      id: 135,
      name: '毛线帽',
      // fonts: [{ text: '3' }],
    },
    {
      id: 136,
      name: '墨迹会员月卡',
      // fonts: [{ text: '3' }],
    },
    {
      id: undefined,
      name: '感谢参与',
      // fonts: [{ text: '4' }],
    },
    {
      id: 137,
      name: '不感帽',
      // fonts: [{ text: '5' }],
    },
  ])

  // 获取抽奖信息
  const { data: rewardLogData, refetch: refetchRewardLog } = useQuery(
    ['get/draw/info'],
    RewardLog,
  )

  // 抽奖
  const { mutateAsync: mutateReward } = useMutation(RewardV2, {
    onSuccess: async (res) => {
      if (!res)
        return

      const prizeId = res.data.lottery_result
      myLucky.current && myLucky.current.play() // ?开启转盘

      // 获取最新的抽奖次数
      const { data: user } = await refetchUser()

      // ?没有中奖但是有抽奖次数
      if (!prizeId && user && user?.cj_num > 0)
        return myLucky.current.stop(1) // ?停止到再来一次

      // ?没有中奖也没有抽奖次数
      if (!prizeId)
        return myLucky.current.stop(4)

      // 匹配奖品
      const index = prizes.findIndex(
        prize => prize.id === prizeId,
      )

      // 没有匹配到则停留到没有中奖
      if (index !== -1)
        myLucky.current.stop(index)
      else myLucky.current.stop(4)

      refetchRewardLog() // 刷新中奖结果
    },
  })

  const { renderNode: renderCaptchaNode, open: openCaptcha } = useCaptchaBox({
    async onSuccess() {
      setIsSpinning(true)
      await mutateReward() // ?开始抽奖
      refetchUser()
    },
  })

  const [blocks] = useState([
    {
      imgs: [
        {
          src: DrawBg,
          width: '100%',
          height: '100%',
          rotate: true,
        },
      ],
    },
  ])

  return (
    <>
      <div id="captcha-element"></div>

      <XyzTransitionGroup
        duration="auto"
        appear
        appearVisible
        xyz="fade"
        className="flex flex-col items-center min-h-screen pt-[50px] pb-[50px] bg-bottom bg-cover"
        style={{
          backgroundImage: `url(${BgImage})`,
        }}
      >
        <div>
          <ChannelLogo />
        </div>

        <img
          src={Title}
          className={classNames(
            'block w-[500px]',
          )}
        />

        <img
          src={Subtitle}
          className={classNames(
            'block w-[300px]',
          )}
        />

        <div
          className="flex relative flex-col justify-center items-center mt-3"
        >
          <img
            src={DrawStartButton}
            id="submit"
            onClick={async () => {
              if (isSpinning)
                return

              if (user?.cj_num === 0)
                return Toast.fail('今天您已暂无抽奖机会')

              openCaptcha() // 使用行为验证

              // ?代表用户的剩余抽奖次数为0， 并且已经有中奖记录了，但是也没有中奖
              if (user?.cj_num === 0 && rewardLogData?.lottery_result === 0) {
                history.push('/result/thanks')
                return Toast('今日抽奖次数已用完')
              }
            }}
            className=" w-[200px] absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-10 -mt-[70px]"
            alt=""
          />

          <LuckyWheel
            ref={myLucky}
            width="280px"
            height="280px"
            blocks={blocks}
            prizes={prizes}
            onEnd={(prize: any) => {
              setIsSpinning(false)
              if (prize.id === 999) // ?再来一次
                return

              setTimeout(() => {
                if (!prize.id)
                  return history.push('/result/thanks')

                history.push('/result')
              }, 1000)
            }}
          />

          <img
            src={DrawDipan}
            className=" block w-[500px] -mt-[50px] pointer-events-none"
            alt=""
          />

          <i
            className={classNames(
              styles.kang,
              'bg-cover bg-no-repeat w-[227px] h-[400px] -ml-[500px] -mt-[360px] z-10',
            )}
          />

        </div>
      </XyzTransitionGroup>

      {
        Boolean(rewardLogData?.lottery_result) && <img onClick={() => history.push('/result')} src={MyPrizeButton} className="absolute top-2 left-2 w-[80px] z-10" alt="我的奖品" />
      }

      <div className="absolute right-0 bottom-0">
        <MallLinkButton />
      </div>

      {renderCaptchaNode()}
    </>
  )
}
